package com.bk.ouatadmin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.bk.ouatadmin.common.PageUtil;
import com.bk.ouatadmin.dto.ContentsDto;
import com.bk.ouatadmin.service.ContentsService;
import com.bk.ouatadmin.service.UserService;
import com.mysql.jdbc.StringUtils;

@Controller
public class ContentsController {
	
	private static final Logger logger = LoggerFactory.getLogger(ContentsController.class);
	
	@Autowired
	private ContentsService contentsService;
	
	@Autowired
	private PageUtil pageUtil;
	
	/** 페이지 처리
	 * @param paramsMap
	 * @param boardMap
	 * @return
	 */
	private int setPage(ContentsDto contents) {
		int pageNum = 1; //시작글 번호
		Object obj = contents.getPageNum();
		if(obj != null){
			try {
				pageNum = Integer.valueOf(obj.toString());
			} catch (NumberFormatException nfe) {
				nfe.printStackTrace();
			}
		}
		contents.setStartRownum( (pageNum - 1) * PageUtil.PER_PAGE);
		contents.setPerPage( PageUtil.PER_PAGE);
		return pageNum;
	}
	
	@RequestMapping(value="contents/list.do") 
	public ModelAndView list(ContentsDto contents) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("contents/list");

		//페이징 로직
		int totalCnt = contentsService.count(contents);
		int pageNum = setPage(contents);
		mav.addObject("pageLink", pageUtil.setPageLink(totalCnt, pageNum));
		//페이징 로직
		
		mav.addObject("list", contentsService.list(contents));

		return mav;
	}
			
	@RequestMapping(value="contents/detail.do")
	public ModelAndView detail(ContentsDto contentsDto) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("contents/create");
		
		return mav;
	}
	
	@RequestMapping(value="contents/create.do")
	public String create(Model model) {
		return null;
	}
	
	@RequestMapping(value="contents/createAction.do")
	public String createAction(ContentsDto contentsDto, HttpSession session) {
		
		HashMap<String, String> sessionMap = (HashMap<String, String>)session.getAttribute("login_session");
		contentsDto.setReg_member_id(sessionMap.get("MEMBER_ID"));
		contentsService.insert(contentsDto);
		
		return "redirect:/contents/list.do";
	}
}
